package com.tous.tool.controller;

import com.tous.tool.service.HlsConversionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;

/**
 * @author mengwei
 * @description HlsStreamController
 * @createDate 2025/7/21 11:41
 */

@RestController
@RequestMapping("/api/hls")
public class HlsStreamController {

    @Autowired
    private HlsConversionService hlsService;

    @Value("${video.hls.output-dir:hls_output}")
    private String outputDir;

    @GetMapping("/prepare/{videoName}")
    public String prepareHlsStream(@PathVariable String videoName) throws IOException {
        File inputFile = new File("videos/" + videoName);
        hlsService.convertToHls(inputFile, videoName.replace(".", "_"));
        return "HLS stream prepared";
    }

    @GetMapping("/{videoName}/{quality}/{filename}")
    public Resource getHlsSegment(
            @PathVariable String videoName,
            @PathVariable String quality,
            @PathVariable String filename) {

        String filePath = outputDir + File.separator +
                videoName.replace(".", "_") + File.separator +
                quality + File.separator + filename;

        return new FileSystemResource(filePath);
    }

    @GetMapping("/{videoName}/playlist.m3u8")
    public Resource getMasterPlaylist(@PathVariable String videoName) {
        String filePath = outputDir + File.separator +
                videoName.replace(".", "_") + File.separator +
                "playlist.m3u8";

        return new FileSystemResource(filePath);
    }
}
